<?php

namespace App\Http\Livewire\Tags;

use App\Models\Archive;
use Livewire\Component;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Edit extends Component
{
    use AuthorizesRequests;
    public $archive;
    public $tags;
    public $tag;
    public $message;

    public function mount(Archive $archive)
    {
        $this->archive = $archive;
        $this->tags = $this->getTags();
    }
    public function getTags()
    {
        return $this->archive->tags->map(function ($tag) {
            return [
                'name' => $tag->name,
                'slug' => $tag->slug,
                'id' => $tag->id
            ];
        });
    }
    public function save()
    {
        $this->authorize('update', $this->archive);
        $this->validate([
            'tag' => 'required',
        ]);
        $this->archive->tag($this->tag);
        $this->tags = $this->getTags();
        $this->message = 'Added.';
        $this->emit('showMessage', [
            'content' => '标签 ' . $this->tag . ' 已添加'
        ]);
        $this->emit('close');
        $this->tag = '';
    }
    public function remove($tag)
    {
        $this->authorize('update', $this->archive);
        $this->archive->untag($tag);
        $this->emit('showMessage', [
            'content' => '标签 ' . $this->tag . ' 已移除'
        ]);
        $this->tags = $this->getTags();
    }
    public function render()
    {
        return view('livewire.tags.edit');
    }
}
